package com.cx.mall.user.service.impl;

import com.cx.mall.common.utils.IpUtils;
import com.cx.mall.common.utils.ResponseEnum;
import com.cx.mall.common.model.user.UserInfo;
import com.cx.mall.common.model.user.UserLoginLog;
import com.cx.mall.user.service.ILoginService;
import com.cx.mall.user.service.IUserInfoService;
import com.cx.mall.user.service.IUserLoginLogService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserLoginLogService userLoginLogService;
    @Override
    public UserInfo login(String username, String password) {
        //1、到数据表查询用户是否存在
        UserInfo userInfo = userInfoService.getUserInfoByUsername(username);
        //2、如果存在比较密码
        //3、如果密码相同返回用户信息
        if (userInfo == null) {
            throw new RuntimeException(ResponseEnum.USER_ACCOUNT_FORBIDDEN.getMessage());
        }
        if (!BCrypt.checkpw(password, userInfo.getPassword())) {
            throw new RuntimeException(ResponseEnum.USER_PASSWORD_ERROR.getMessage());
        }
        //4、写登录日志表
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUserId(userInfo.getId());
        userLoginLog.setIp(IpUtils.getClientIp()); //模拟IP
        userLoginLogService.save(userLoginLog);
        return userInfo;
    }
}
